package lsf.itcast.service.imp;

import lsf.itcast.dao.UserDao;
import lsf.itcast.domain.Role;
import lsf.itcast.domain.UserInfo;
import lsf.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImp implements UserService {
    @Autowired
    private UserDao userDao;
    // //配置加密后台的密码
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void save(UserInfo userInfo) {
        //配置加密后台的密码
        String encodePassword = bCryptPasswordEncoder.encode(userInfo.getPassword());
        userInfo.setPassword(encodePassword);
        userDao.save(userInfo);
    }

    @Override
    public void addRoleToUser(String userId, String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            userDao.addRoleToUser(userId,ids[i]);
        }
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUserId(username);
        //获取角色
        List<Role> roles = userInfo.getRoles();

        //获取数据库中的用户名，密码，以及状态，跟用户权限
        User user = new User(userInfo.getUsername(),userInfo.getPassword(),
                userInfo.getStatus()==0? false:true,true,true,true,getAuthority(roles));
        return user;
    }

  private List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
      List<SimpleGrantedAuthority> authoritys = new ArrayList();
      for (Role role : roles) {
          authoritys.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
      }

      return authoritys;
  }

        //查询所有用户
    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }
   //查询用户详情，包含了用户角色和权限
    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }

}
